package com.lib.smartimage;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.lib.okhttp.NetClient;
import com.lib.utils.ImageUtils;
import com.lib.utils.XLog;

import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class WebSmartImage implements ISmartImage {
    private static WebSmartImageCache imageCache;

    private Call mCall;
    private String mUrl;
    private int mWidth;

    WebSmartImage(String url) {
        mUrl = url;
    }

    /**
     * @param url
     * @param width 需要的宽，高会自动计算
     */
    WebSmartImage(String url, int width) {
        mUrl = url;
        mWidth = width;
    }

    public Bitmap getBitmap(Context context) {
        if (imageCache == null) {
            imageCache = new WebSmartImageCache();
        }
        // Try getting bitmap from cache first
        Bitmap bitmap = null;
        if (mUrl != null) {
            bitmap = imageCache.getBitmap(mUrl, mWidth);

            if (bitmap == null && mUrl.contains("http")) {
                bitmap = getBitmapFromUrl(mUrl);
                if (bitmap != null) {
                    imageCache.cacheBitmapToDisk(mUrl, bitmap);
                    if (mWidth > 0) {
                        bitmap = ImageUtils.scale(bitmap, mWidth, true);
                    }
                    imageCache.cacheBitmapToMemory(mUrl, bitmap);
                }
            }
        }
        return bitmap;
    }

    @Override
    public void setCancel(boolean cancel) {
        if (mCall != null) {
            mCall.cancel();
        }
    }

    private Bitmap getBitmapFromUrl(String url) {
        Request request = NetClient.getCommonReqBuilder()
                .url(url)
                .build();

        mCall = NetClient.getFileOkHttpClient().newCall(request);

        Bitmap bitmap = null;
        try (Response response = mCall.execute();) {
            ResponseBody responseBody = response.body();
            InputStream is = responseBody.byteStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (Exception e) {
            XLog.w("getBitmapFromUrl" + Log.getStackTraceString(e));
        }
        return bitmap;
    }

    public static void removeFromCache(String url) {
        if (imageCache != null) {
            imageCache.remove(url);
        }
    }
}
